package cn.wolfcode.plus.service.impl;

import cn.wolfcode.plus.domain.RedPacketInfo;
import cn.wolfcode.plus.service.IRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

@Service
public class RedisServiceImpl implements IRedisService {

    @Autowired
    private StringRedisTemplate template;

    private final String prefix = "redPacket:id:";
    private final String amount = ":amount";
    private final String count = ":count";

    @Override
    @Transactional
    public void save(RedPacketInfo redPacketInfo) {
        // 红包数量
        ValueOperations<String, String> valueOperations = template.opsForValue();
        valueOperations.setIfAbsent(prefix+redPacketInfo.getId()+count,redPacketInfo.getTotalPacket().toString());
        // 红包金额
        valueOperations.setIfAbsent(prefix+redPacketInfo.getId()+amount,redPacketInfo.getTotalAmount().toString());
    }

    @Override
    public int getRemainCount(RedPacketInfo redPacketInfo) {

        return Integer.parseInt(Optional.ofNullable(template.opsForValue().get(prefix + redPacketInfo.getId() + count)).orElse("0"));
    }

    @Override
    public int getRemainAmount(RedPacketInfo redPacketInfo) {
        return Integer.parseInt(Optional.ofNullable(template.opsForValue().get(prefix+redPacketInfo.getId()+amount)).orElse("0"));
    }

    @Override
    public void decr(Integer id, int randomMoney) {
        template.opsForValue().decrement(prefix + id + count);
        template.opsForValue().decrement(prefix + id + amount,randomMoney);
    }

    @Override
    public void decrAmount(Integer id) {
        template.opsForValue().decrement(prefix + id + count);
    }
}
